package com.angle.im.server.config.mq.listeners;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.angle.im.server.config.mq.domain.SendToOneMqBody;
import com.angle.im.server.domain.ImServer;
import com.angle.im.server.service.ServerService;
import com.angle.im.server.service.SocketServer;
import com.angle.im.server.utils.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangwei
 * @date 2019/4/15 17:49
 * @desc 点对点消息监听
 */
@Component
public class SendOneListener implements MessageListener {

    @Autowired
    private ServerService serverService;
    @Autowired
    private SocketServer socketServer;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        /*
         * 0 判断用户是否是本机的链接用户
         * 1 获取目标用户session
         * 2 发送消息
         * 3 保存消息
         */
        SendToOneMqBody sendToOneMqBody = CommonUtils.byteArrToObj(message.getBody(), SendToOneMqBody.class);
        String platform = sendToOneMqBody.getPlatform();
        String to = sendToOneMqBody.getTo();
        String serverId = serverService.getServerIdByUserId(platform, to);
        //如果用户所绑定的服务id不是本机，则跳出
        if (StringUtils.isBlank(serverId) || !serverId.equals(ImServer.INSTANCE.LOCAL_SERVER_ID)) {
            return Action.CommitMessage;
        }
        socketServer.sendToOne(sendToOneMqBody.getFrom(),sendToOneMqBody.getTo(),sendToOneMqBody.getMsg());
        return Action.CommitMessage;
    }
}
